\input{euler.tex}

\usepackage{color}
\newcommand{\R}[1]{\color{red}{#1}}

\begin{document}

\problem[28]{Sum of Diagonals in a Spiral}

Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:

\begin{center}
\begin{tabular}{c c c c c}
\R{21} & 22 & 23 & 24 & \R{25} \\
20 &  \R{7} &  8 &  \R{9} & 10 \\
19 &  6 &  \R{1} &  2 & 11 \\
18 &  \R{5} &  4 &  \R{3} & 12 \\
\R{17} & 16 & 15 & 14 & \R{13} \\
\end{tabular}
\end{center}

It can be verified that the sum of the numbers on the diagonals is 101.

What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?

\solution

We find the sum by adding up the numbers in the corner of each square from the center to the border. Let $S(n)$ denote the sum of corners of the $n$th square. The first few terms of $S(n)$ are:
\begin{align}
S(0) &= 1 , \notag \\
S(1) &= 3+5+7+9 = (1+9) \times 5 / 2 - 1 , \notag \\
S(2) &= 13+17+21+25 = (9+25) \times 5 / 2 - 9 . \notag
\end{align}
Thus we find
\begin{align}
S(0) &= 1 , \notag \\
S(n) &= \frac{[ (2n-1)^2 + (2n+1)^2 ] \times 5}{2} - (2n-1)^2 \notag \\
&= 4(4n^2+n+1) . \notag
\end{align}
It follows that the sum of diagonals is
\[
\sum_{k=0}^{n} S(k) = \frac{8n(n+1)(2n+1)}{3} + 2n(n+1) + 4n + 1 .
\]

\complexity

Time complexity: $\BigO(1)$.

Space complexity: $\BigO(1)$.

\answer 

669171001

\end{document} 
